package com.ghpt.component;

import com.opencsv.CSVReader;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class CsvParser {

    public List<Map<String, Object>> parseCsv(MultipartFile file) throws Exception {
        List<Map<String, Object>> dataList = new ArrayList<>();
        try (CSVReader reader = new CSVReader(new InputStreamReader(file.getInputStream()))) {
            String[] nextLine;
            boolean isHeader = true;

            while ((nextLine = reader.readNext()) != null) {
                if (isHeader) {
                    validateHeader(nextLine);
                    isHeader = false;
                    continue;
                }

                if (nextLine.length >= 2) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("id", Long.parseLong(nextLine[0]));
                    data.put("value", Double.parseDouble(nextLine[1]));
                    dataList.add(data);
                }
            }
        }
        return dataList;
    }

    private void validateHeader(String[] header) {
        if (header.length < 2 ||
                !header[0].equalsIgnoreCase("id") ||
                !header[1].equalsIgnoreCase("value")) {
            throw new IllegalArgumentException("CSV文件必须包含id,value列");
        }
    }
}